<?php

declare(strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Kernel\Util;

use App\Constants\Constants;
use App\Dao\StoreDao;
use App\Model\Store;
use App\Exception\BusinessException;

use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Context;
use Hyperf\Utils\Traits\StaticInstance;

use Firebase\JWT\JWT;

/**
 * 后台用户jwt服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\Instance
 */
class StoreJwtInstance
{
    use StaticInstance;

    CONST KEY = 'mBC5v1sOKVvbdEitdSBenu59nfNfhwkedkJVNabosTw=';

    /**
     * @var int
     */
    public $user_id;

    /**
     * @var User
     */
    public $user;

    /**
     * 构建token
     *
     * @param $userModel
     * @return string
     */
    public function encode($userModel)
    {
        $this->user_id = (int)$userModel->id;
        $this->user = $userModel;

        return JWT::encode([
            'iss' => '',
            'iat' => time(),
            'exp' => time() + Constants::TOKEN_EXPIRE,
            'id' => $userModel->id
        ], self::KEY);
    }

    /**
     * 解析token
     *
     * @param string $token
     * @return $this
     */
    public function decode(string $token): self
    {
        if( empty($token) ) {
            throw new BusinessException(401, __('api.COMMON.NO_LOGIN'));
        }
        $decode = (array)JWT::decode($token, self::KEY, ['HS256']);

        if ($decode['exp'] < time()) {
            throw new BusinessException(401, __('api.USER.LOGIN_EXPIRED'));
        }

        if ($id = $decode['id'] ?? null) {
            $this->user_id = $id;
            $this->user = ApplicationContext::getContainer()->get(StoreDao::class)->first((int)$id);

            // token续期
            if ($decode['exp'] - time() <= Constants::TOKEN_REFRESH) {
                Context::set('refresh_token', (string)$this->encode($this->user));
            }
        }

        return $this;
    }

    public function build(): self
    {
        if (empty($this->user_id)) {
            throw new BusinessException(401, __('api.USER.NEED_LOGIN'));
        }

        return $this;
    }

    public function getId(): ?int
    {
        return $this->user_id;
    }

    public function getStore(): ?Store
    {
        if ($this->user === null && $this->user_id) {
            $this->user = ApplicationContext::getContainer()->get(StoreDao::class)->first($this->user_id);
        }

        return $this->user;
    }
}